package com.example.linyiquan.app.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.example.linyiquan.app.R;
import com.example.linyiquan.app.adapter.GridAdapter;
import com.example.linyiquan.app.beam.AppBeam;
import com.example.linyiquan.app.util.Utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by linyiquan on 17-4-15.
 */

public class GridActivity extends Activity {

    //
    private GridView gridView;
    private List<AppBeam> list = new ArrayList<>();
    private GridAdapter gridAdapter;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor spe;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridview);

        sharedPreferences = getPreferences(0);
        spe = sharedPreferences.edit();

        initApps();
        initGrid();

    }

    //初始化已经添加的应用
    private void initApps() {
        List<AppBeam> apps = Utils.getApps(this);
        Set<String> appPackages = sharedPreferences.getStringSet("appPackages", new HashSet<String>());
        Iterator iterator = appPackages.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            String packageName = (String) iterator.next();
            for (int i = 0; i < apps.size(); i++) {
                if (apps.get(i).getPackageInfo().equals(packageName)) {
                    list.add(apps.get(index));
                }
            }
            index++;
        }
    }

    protected void onStop() {
        super.onStop();
    }

    /**
     * 保存已经添加在视图里的app
     */
    private void saveData() {
        Set<String> appPackages = new HashSet<>();
        for (int i = 0; i < list.size() - 2; i++) {
            appPackages.add(list.get(i).getPackageInfo());
        }
        spe.putStringSet("appPackages", appPackages);
        spe.apply();
    }

    /**
     * 添加,删除应用
     */
    private void initGrid() {
        gridView = (GridView) findViewById(R.id.gridview);//获取控件
        gridAdapter = new GridAdapter(this, list);//对象初始化
        gridView.setAdapter(gridAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == gridAdapter.getCount() - 1) {//删除应用
                    String[] items = new String[list.size() - 2];
                    for (int i = 0; i < list.size() - 2; i++) {
                        items[i] = list.get(i).getAppName();
                    }
                    new AlertDialog.Builder(GridActivity.this)
                            .setTitle("Delete your app")
                            .setItems(items, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    list.remove(which);
                                    gridAdapter.notifyDataSetChanged();
                                    saveData();
                                }
                            }).show();

                } else if (position == gridAdapter.getCount() - 2) {//添加应用
                    final List<AppBeam> apps = Utils.getApps(GridActivity.this);
                    String[] items = new String[apps.size()];
                    for (int i = 0; i < apps.size(); i++) {
                        items[i] = apps.get(i).getAppName();
                    }
                    new AlertDialog.Builder(GridActivity.this)
                            .setTitle("add your app")
                            .setItems(items, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    list.add(list.size() - 2, apps.get(which));
                                    gridAdapter.notifyDataSetChanged();
                                    saveData();
                                }
                            }).show();

                } else {
                    try {
                        PackageManager pm = GridActivity.this.getPackageManager();
                        Intent intent = pm.getLaunchIntentForPackage(list.get(position).getPackageInfo());
                        GridActivity.this.startActivity(intent);
                    } catch (Exception e) {
                        Toast.makeText(GridActivity.this, "启动应用失败", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });
    }
}
